import { auth } from "@/api";
import { ProfessorInfoUtils, ProfessorTokenUtils } from "@/common/utils";
import store from "../index";


const state = {
  professorInfo: ProfessorInfoUtils.getProfessorInfo(),
  token: ProfessorTokenUtils.getToken(),
};

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
    ProfessorTokenUtils.setToken(token);
  },

  SET_PROFESSOR_INFO: (state, professorInfo) => {
    state.professorInfo = professorInfo;
    ProfessorInfoUtils.setProfessorInfo(professorInfo);
  },

  CLEAR_PROFESSOR_INFO: (state) => {
    state.professorInfo = null;
    state.token = null;
    ProfessorInfoUtils.removeProfessorInfo();
    ProfessorTokenUtils.removeToken();
  },
};

const actions = {
  // 登录
  async login({ commit }, loginData) {
    try {
      const { data, success, msg } = await auth.getPermissionConfirm(
        loginData
      );
      if (success && data && data.token) {
        // 清除 user 信息
        store.commit("user/CLEAR_USER_INFO");
        // 设置 token
        commit("SET_TOKEN", data.token);
        //过滤数据
        const professorInfo = data.professorInfo;
        commit("SET_PROFESSOR_INFO", professorInfo);
        return;
      }
      return Promise.reject({
        msg: msg || "登录失败，请检查输入是否有误",
        type: ERROR_TYPE.BUSINESS,
      });
    } catch (error) {
      return Promise.reject(error);
    }
  }
};

const professor = {
  namespaced: true,
  state,
  mutations,
  actions,
};

export default professor;
